//
//  FinalPlayViewController.m
//  CoJellyCartoon
//
//  Created by kingbw on 16/4/7.
//  Copyright © 2016年 CJG. All rights reserved.
//

#import "FinalPlayViewController.h"
#import "VideoPlayer.h"
#import "STL_PlayerRecognizer.h"
@interface FinalPlayViewController ()<STL_PlayRecognizerDelegate>

@property (nonatomic, strong) VideoPlayer *player;
@property (nonatomic, strong) UIView *playView;
@property (nonatomic, strong) UIButton *playBtn;
@property (nonatomic, strong) UISlider *slider;
@property (nonatomic, strong) UILabel *startLabel;
@property (nonatomic, strong) UILabel *endLabel;
@property (nonatomic, strong) UIButton *backBtn;
@property (nonatomic, strong) UILabel *headline;

@property (nonatomic, strong) UIView *blackView;
@property (nonatomic, strong) UIView *blackViewTwo;

@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) NSTimer *tttimer;

@property (nonatomic, assign) BOOL isPlay;
@property (nonatomic, assign) BOOL isTouch;

@property (nonatomic, assign) float brightValue; //亮度
// 缓冲进度条
@property (nonatomic, strong) UIProgressView *progressView;

@property (nonatomic, strong) NSString *playUrl;
@property (nonatomic, strong) NSString *Cid;

@property (nonatomic, assign) CGPoint startPoint;

@property (nonatomic, assign) CGFloat totalDuration;
@property (nonatomic, assign) NSTimeInterval timeInterval;


@end

@implementation FinalPlayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //(@"%f%f",self.view.bounds.size.width,self.view.bounds.size.height);
    self.brightValue = [UIScreen mainScreen].brightness;
    
    [self finalFirstRequest];
    
    self.isPlay = NO;
    self.isTouch = YES;
    
    [self creatPlayer];
    [self GesAction];
    
    [self creatBlackView];
    [self creatBlackViewTwo];
    
    [self creatBackBtn];
    [self creatPlayBtn];
    
    [self creatTimeAndHeadlineLabel];
    [self createProgressView];
    [self creatSlider];
    

    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeAction) userInfo:nil repeats:YES];
    
    self.tttimer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(blackViewDisappear) userInfo:nil repeats:NO];
    
}

//单独定制白色电池条
- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}
//隐藏顶部状态栏
- (BOOL)prefersStatusBarHidden {
    return YES;
}
- (void)creatPlayer {
    self.player = [VideoPlayer shareAVPlayer];
    
//    self.player.volume = 0.5f;
    [self.player playWithUrl:self.playUrl];
    [self.player play];
    
    self.playView = [[UIView alloc] initWithFrame:self.view.bounds];
    self.playView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.playView];
    
    // 播放页面
    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    playerLayer.frame = CGRectMake(ScreenWidth / 2 - ScreenHeight / 2, ScreenHeight / 2 - ScreenWidth / 2, ScreenHeight, ScreenWidth);
    
    // 旋转至全屏
    playerLayer.transform = CATransform3DMakeRotation(M_PI_2, 0, 0, 1);
    
    
    // 设置显示图层视频的宽高比自动适应播放窗口的大小
    playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
    
    [self.playView.layer addSublayer:playerLayer];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    // 执行方法需要点击（轻拍）的次数
    tap.numberOfTapsRequired = 1;
    // 需要几个手指点击（轻拍）
    tap.numberOfTouchesRequired = 1;
    
    // 将手势赋给视图
    [self.playView addGestureRecognizer:tap];
    
}

#pragma mark - 数据请求播放网址
- (void)finalFirstRequest {
    //(@"!!!%@", [NSString stringWithFormat:@"http://www.bilibilijj.com/Api/AvToCid/%@", self.Aid]);
    [WZAFNetTool GetNetWithURL:[NSString stringWithFormat:@"http://www.bilibilijj.com/Api/AvToCid/%@", self.Aid] WithBody:nil headfile:nil response:WZJSON success:^(id reuslt) {
        
        self.headline.text = reuslt[@"title"];
        //(@"标题%@", self.headline);
        NSArray *arr = reuslt[@"list"];
        NSDictionary *dic = arr[0];
        self.Cid = [dic objectForKey:@"CID"];
        
//        //(@"666%@", self.Cid);
        [self finalSecondRequest];
    } failure:^(NSError *error) {
        
    }];
    
    
}


#pragma mark - 解最后播放网址
- (void)finalSecondRequest {
    
    [WZAFNetTool GetNetWithURL:[NSString stringWithFormat:@"http://interface.bilibili.com/playurl?platform=android&_device=android&_hwid=831fc7511fa9aff5&_tid=0&_p=1&_down=0&quality=3&otype=json&appkey=86385cdc024c0f6c&type=mp4&sign=7fed8a9b7b446de4369936b6c1c40c3f&_aid=%@&cid=%@", self.Aid, self.Cid] WithBody:nil headfile:nil response:WZJSON success:^(id reuslt) {
                
        NSArray *arr = reuslt[@"durl"];
        NSDictionary *dic = arr[0];
        self.playUrl = [dic objectForKey:@"url"];
        //(@"播放%@", self.playUrl);
        
        [self.player playWithUrl:self.playUrl];
        [self.player play];
    } failure:^(NSError *error) {
        
    }];
}

//下面透明栏
- (void)creatBlackView {
    self.blackView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth * 50 / 414, ScreenHeight)];
    self.blackView.backgroundColor = [UIColor blackColor];
    self.blackView.alpha = 0.5;
    [self.playView addSubview:self.blackView];
    
}

//上面透明栏
- (void)creatBlackViewTwo {
    self.blackViewTwo = [[UIView alloc] initWithFrame:CGRectMake(ScreenWidth - ScreenWidth * 50 / 414, 0, ScreenWidth * 50 / 414, ScreenHeight)];
    self.blackViewTwo.backgroundColor = [UIColor blackColor];
    self.blackViewTwo.alpha = 0.5;
    [self.playView addSubview:self.blackViewTwo];
    
}

- (void)blackViewDisappear {
    self.blackView.hidden = YES;
    self.blackViewTwo.hidden = YES;
    self.isTouch = YES;
}

//返回按钮
- (void)creatBackBtn {
    self.backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.backBtn.frame = CGRectMake(ScreenWidth * 10 / 414, ScreenHeight * 20 / 736, ScreenWidth * 32 / 414, ScreenHeight * 32 / 746);
    [self.backBtn setImage:[UIImage imageNamed:@"newBack"] forState:UIControlStateNormal];
    [self.blackViewTwo addSubview:self.backBtn];
    //按钮旋转90度
    self.backBtn.transform = CGAffineTransformMakeRotation(M_PI_2);
    [self.backBtn addTarget:self action:@selector(backBtnAction:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)backBtnAction:(UIButton *)sender {
    [self.player pause];
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

//播放按钮
- (void)creatPlayBtn {
    self.playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.playBtn.frame = CGRectMake(ScreenWidth * 10 / 414, ScreenHeight * 20 / 736, ScreenWidth * 32 / 414, ScreenHeight * 32 / 736);
    [self.playBtn setImage:[UIImage imageNamed:@"newPause"] forState:UIControlStateNormal];
    [self.blackView addSubview:self.playBtn];
    //按钮旋转90度
    self.playBtn.transform = CGAffineTransformMakeRotation(M_PI_2);
    [self.playBtn addTarget:self action:@selector(playBtnAction:) forControlEvents:UIControlEventTouchUpInside];
}

//时间
- (void)creatTimeAndHeadlineLabel {
    self.startLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 60, 50, 40)];
    self.startLabel.textColor = [UIColor whiteColor];
    self.startLabel.transform = CGAffineTransformMakeRotation(M_PI_2);
    [self.blackView addSubview:self.startLabel];
    
    self.endLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, ScreenHeight - 50, 50, 40)];
    self.endLabel.textColor = [UIColor whiteColor];
    self.endLabel.transform = CGAffineTransformMakeRotation(M_PI_2);
    [self.blackView addSubview:self.endLabel];
    
    self.headline = [[UILabel alloc] initWithFrame:CGRectMake(ScreenWidth * (-300) / 414, ScreenHeight * 370 / 736, ScreenWidth * 650 / 414, ScreenHeight * 30 / 746)];
    self.headline.transform = CGAffineTransformMakeRotation(M_PI_2);
    self.headline.textColor = [UIColor whiteColor];
    [self.blackViewTwo addSubview:self.headline];
    
}
//滑动条
- (void)creatSlider {
    self.slider = [[UISlider alloc] initWithFrame:CGRectMake(0, 0, ScreenHeight - 160, 5)];
    
    [self.blackView addSubview:self.slider];
    //设置最大值
    self.slider.maximumTrackTintColor = [UIColor clearColor];
    self.slider.minimumValue = 0.0f;
    self.slider.maximumValue = 1.0f;
    self.slider.transform = CGAffineTransformMakeRotation(M_PI_2);
    self.slider.center = CGPointMake(self.playBtn.center.x, self.view.center.y + 20);
    
    [self.slider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];

}

//缓冲条
- (void)createProgressView {
    self.progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, ScreenHeight - 170, 5)];
    self.progressView.transform = CGAffineTransformMakeRotation(M_PI_2);
    self.progressView.center = CGPointMake(self.playBtn.center.x, self.view.center.y + 20);
    self.progressView.tintColor = [UIColor blueColor];
    [self.blackView addSubview:self.progressView];
}

- (void)sliderAction:(UISlider *)sender {
    
    //    CMTimeMakeWithSeconds
    //    参数1:跳转到的时间
    //    参数2:每秒多少帧 （fps）
    if (self.player.currentItem.duration.value) {
        [self.player seekToTime:CMTimeMakeWithSeconds(self.player.currentItem.duration.value / self.player.currentItem.duration.timescale * self.slider.value, self.player.currentTime.timescale) completionHandler:^(BOOL finished) {
            [self.player play];
        }];
    }
    
}
- (void)timeAction {
    
    CMTime presentTime = self.player.currentItem.currentTime;
    
    CMTime totalTime = self.player.currentItem.duration;
    
    CGFloat presentFloatTim = (CGFloat)presentTime.value/presentTime.timescale;
    
    CGFloat totalFloatTim = (CGFloat)totalTime.value / totalTime.timescale;
    
    self.slider.value = presentFloatTim / totalFloatTim;
    
    NSDate *presentDate = [NSDate dateWithTimeIntervalSince1970:presentFloatTim];
    NSDate *totalDate = [NSDate dateWithTimeIntervalSince1970:totalFloatTim];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    if (totalFloatTim / 3600 >= 1) {
        [formatter setDateFormat:@"HH:mm:ss"];
    }else {
        [formatter setDateFormat:@"m:ss"];
    }
    
    NSString *presentStrTime = [formatter stringFromDate:presentDate];
    NSString *totalStrTime = [formatter stringFromDate:totalDate];
    
    self.startLabel.text = presentStrTime;
    self.endLabel.text = totalStrTime;
    
    self.totalDuration = CMTimeGetSeconds(totalTime);
    
    NSString *str = [NSString stringWithFormat:@"%f", self.totalDuration];
    
    if ([str isEqualToString:@"nan"]) {
        self.totalDuration = 1;
    }
    
     self.timeInterval = [self availableDuration];
//    //(@"Time Interval:%f",self.timeInterval);
    
    if (presentStrTime == totalStrTime) {
        
        [self dismissViewControllerAnimated:YES completion:^{
            
        }];
    }
    NSString *stri = [NSString stringWithFormat:@"%f", self.timeInterval];
    if ([stri isEqualToString:@"nan"]) {
        self.timeInterval = 0;
    }
    
    
//    CMTime duration11 = self.player.currentItem.duration;
//    CGFloat totalDuration = CMTimeGetSeconds(totalTime);
    //(@"totalDuration %f",  self.totalDuration);
    [_progressView setProgress:self.timeInterval / self.totalDuration animated:YES];
    
    
}

// 计算缓冲进度
- (NSTimeInterval)availableDuration {
    NSArray *loadedTimeRanges = [[self.player currentItem] loadedTimeRanges];
    CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue];// 获取缓冲区域
    float startSeconds = CMTimeGetSeconds(timeRange.start);
    float durationSeconds = CMTimeGetSeconds(timeRange.duration);
    // 计算缓冲总进度
    NSTimeInterval result = startSeconds + durationSeconds;
    
    
    return result;
}

- (void)playBtnAction:(UIButton *)sender {
    
    if (self.isPlay) {
        [self.player play];
        [self.playBtn setImage:[UIImage imageNamed:@"newPause"] forState:UIControlStateNormal];
        self.isPlay = NO;
    } else {
        
        [self.player pause];
        [self.playBtn setImage:[UIImage imageNamed:@"newPlay"] forState:UIControlStateNormal];
        self.isPlay = YES;
    }
    
}

- (void)tapAction:(UITapGestureRecognizer *)tap {
    if (self.isTouch) {
        self.blackView.hidden = NO;
        self.blackViewTwo.hidden = NO;
       
        
        self.tttimer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(blackViewDisappear) userInfo:nil repeats:NO];
       
         self.isTouch = NO;
    }else {
        self.blackView.hidden = YES;
        self.blackViewTwo.hidden = YES;
        self.isTouch = YES;
    }
}

- (void)GesAction {
    
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panAction:)];
    [self.playView addGestureRecognizer:pan];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event  {
    UITouch *touch = [touches anyObject];
    self.startPoint = [touch locationInView:self.view];
}
- (void)panAction:(UIPanGestureRecognizer *)action {
    STL_PlayerRecognizer *playerRecognize = [[STL_PlayerRecognizer alloc] init];
    playerRecognize.startPanPoint = self.startPoint;
    playerRecognize.panDelegate = self;
    [playerRecognize handleSwipe:action withView:self.view];

}

- (void)recognizWithMoveDirection:(STLMoveDirection)direction withChangeValue:(CGFloat)changeValue {
    switch (direction) {
        case STLdirectionUp:
            self.slider.value -= changeValue / ScreenHeight / 5;
            if (self.player.currentItem.duration.value) {
                [self.player seekToTime:CMTimeMakeWithSeconds(self.player.currentItem.duration.value / self.player.currentItem.duration.timescale * self.slider.value, self.player.currentTime.timescale) completionHandler:^(BOOL finished) {
                [self.player play];
                }];
            }
            break;
        case STLdirectionDown:
            self.slider.value += changeValue / ScreenHeight / 5;
            if (self.player.currentItem.duration.value) {
                [self.player seekToTime:CMTimeMakeWithSeconds(self.player.currentItem.duration.value / self.player.currentItem.duration.timescale * self.slider.value, self.player.currentTime.timescale) completionHandler:^(BOOL finished) {
                    [self.player play];
                }];
            }
            break;
        case STLdirectionTopLeft:
            self.brightValue -= changeValue / ScreenWidth / 4;
            [[UIScreen mainScreen] setBrightness:self.brightValue];
            break;
        case STLdirectionTopRight:
            self.brightValue += changeValue / ScreenWidth / 4;
            [[UIScreen mainScreen] setBrightness:self.brightValue];
            break;
        case STLdirectionBottomLeft:
            self.player.volume -= changeValue / ScreenWidth / 5;
            break;
        case STLdirectionBottomRight:
            self.player.volume += changeValue / ScreenWidth / 5;
            break;
        default:
            break;
            
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
